<!--  -->
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{path: '/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>品牌管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row type="flex" justify="space-between">
        <el-col :span="4">
          <el-button type="primary" @click="showDialog">添加品牌</el-button>
        </el-col>
        <el-col :span="6" :pull="1">
          <el-input v-model="query.key" placeholder="搜索名称" clearable @change="queryData">
            <template slot="append">
              <el-button type="danger" size="mini" icon="el-icon-search" cycle @click="queryData"></el-button>
            </template>
          </el-input>
        </el-col>
      </el-row>
      <el-table
        :data="brandList"
        style="width: 100%;margin: 10px 0"
        border
        stripe
        :highlight-current-row="true"
      >
        <el-table-column label="序号" type="index" :index="getIndex"></el-table-column>
        <el-table-column label="名称" prop="name"></el-table-column>
        <el-table-column label="LOGO" prop="image">
          <template slot-scope="scope">
            <img :src="scope.row.image" />
          </template>
        </el-table-column>
        <el-table-column label="首字母" prop="initial"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">Edit</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.row.id)"
            >Delete</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="query.currentPage"
        :page-sizes="[5,10, 20, 50, 100]"
        :page-size="query.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        hide-on-single-page
      ></el-pagination>
    </el-card>
    <el-dialog
      :title="dialogTitle"
      :visible="dialogVisible"
      @close="handleClose('form')"
      :close-on-click-modal="false"
      width="40%"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="120px" label-suffix=":">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入品牌名称"></el-input>
        </el-form-item>
        <el-form-item label="首字母" prop="initial">
          <el-input v-model="form.initial" placeholder="请输入品牌首字母"></el-input>
        </el-form-item>

        <el-form-item label="商品分类" prop="cids" required error="必须选择分类">
          <el-cascader
            v-model="form.cids"
            :options="cateListWithLevel"
            :props="props"
            clearable
            :show-all-levels="false"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="image">
          <!-- <el-upload
            class="logo-uploader"
            action="javascript:;"
            :auto-upload="false"
            :multiple="false"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-exceed="handleExceed"
          >
            <el-button size="mini" type="primary">点击上传图片</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpeg/jpg/png/gif/bmp格式文件 大小不能超过2M </div>
          </el-upload>-->
          <el-upload
            class="upload-demo"
            ref="imgRef"
            action="javascript:;"
            list-type="picture-card"
            :http-request="defaultFileUpload"
            :auto-upload="false"
            :limit="1"
            :on-preview="handlePreview"
            :on-change="fileChange"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
          >
            <el-button size="small" type="primary">Click to upload</el-button>
            <div slot="tip" class="el-upload__tip">jpg/png files with a size less than 500kb</div>
          </el-upload>
          <el-dialog :visible.sync="fileDialogVisible" :modal="false">
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose('form')">取消</el-button>
        <el-button type="primary" @click="submitForm('form')">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      query: {
        key: "",
        currentPage: 1,
        pageSize: 5,
        sortBy: "",
        order: true,
      },
      total: 0,
      brandList: [],
      // dialogTitle: "添加品牌",
      dialogVisible: false,
      form: {
        id: null,
        name: "",
        initial: "",
        cids: [],
        url: "",
      },
      rules: {
        name: [{ required: true, message: "不能为空", trigger: "blur" }],
        initial: [
          { required: true, message: "不能为空", trigger: "blur" },
          {
            pattern: /^[A-Z]{1}$/,
            message: "必须是1个大写字母",
            trigger: ["blur", "change"],
          },
        ],
      },
      cateListWithLevel: [],
      props: {
        multiple: true,
        // checkStrictly: true,
        label: "name",
        value: "id",
      },
      fileDialogVisible: false,
      dialogImageUrl: "",
      uploadFile: {},
    };
  },

  created() {
    this.getBrandList();
    this.queryAllLevel();
  },
  computed: {
    isAdd() {
      return this.form.id == null
    },
    dialogTitle() {
      return this.isAdd ? '添加品牌': '修改品牌'
    }
  },
  methods: {
    getBrandList() {
      this.$http.get("/brand/page", { params: this.query }).then((resp) => {
        // console.log(resp);
        if (!resp.flag) {
          this.$message.warning("查询失败");
        }
        this.brandList = resp.data.items;
        this.total = resp.data.total;
      });
    },
    queryAllLevel() {
      this.$http.get("/category/allLevel").then((resp) => {
        if (!resp.flag) {
          this.$message.warning("查询失败");
          return;
        }
        // console.log(resp);
        this.cateListWithLevel = resp.data;
      });
    },
    queryData() {
      if (!!this.query.key) {
        this.getBrandList();
      }
    },
    getIndex(index) {
      return index + 1;
    },
    handleDelete(id) {
      console.log(id);
    },
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.getBrandList();
    },
    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.getBrandList();
    },
    handleClose(formName) {
      this.clearForm(formName);
      this.hideDialog();
    },
    clearForm(formName) {
      this.$refs[formName].resetFields();
    },
    showDialog() {
      this.dialogVisible = true;
    },
    hideDialog() {
      this.dialogVisible = false;
    },
    handleChange(val) {
      // console.log(val);
      console.log(this.form.cids);
    },
    defaultFileUpload() {},
    beforeUpload(file) {
      const allowTypes = [
        "image/jpeg",
        "image/jpg",
        "image/png",
        "image/bmp",
        "image/gif",
      ];
      const index = allowTypes.findIndex((v) => {
        return v === file.type;
      });
      const isImg = index !== -1;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImg) {
        this.$message.error("Avatar picture must be JPG format!");
      }
      if (!isLt2M) {
        this.$message.error("Avatar picture size can not exceed 2MB!");
      }
      return isImg && isLt2M;
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.fileDialogVisible = true;
    },
    handleRemove(file, fileList) {
      this.uploadFile = {};
    },
    fileChange(file, fileList) {
      this.uploadFile = file.raw;
      // console.log(this.uploadFile);
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$messge.warning("输入信息不正确,请重新填写");
          return;
        }
        // const flag = this.beforeUpload(this.uploadFile);
        // if (!flag) {
        //   return;
        // }
        // 先上传图片
        // 等安装vmware centos7 FastDFS之后再写
        // this.$http.post('/upload/image', this.)
        // console.log(this.form.cids);
        this.form.cids = this.form.cids.map(val => val[2])
        
        console.log(this.form.cids);
        // console.log(this.form.cids);
        this.$http({
          url: '/brand',
          method: this.isAdd ? 'POST': 'PUT',
          data: this.$qs.stringify(this.form)
        }).then(resp => {
          console.log(resp);
        })
      });
    },
  },
};
</script>

<style lang='scss' scoped>
div.logo-uploader {
  width: 102px;
  height: 36px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.logo-uploader:hover {
  border-color: #409eff;
}
.logo-uploader-icon {
  font-size: 20px;
  color: #8c939d;
  width: 102px;
  height: 36px;
  line-height: 36px;
  text-align: center;
}
.logo {
  width: 102px;
  height: 36px;
  display: block;
}
</style>